package calc

import (
	"fmt"
	"strconv"
	"strings"
)

func FloatRound(f float64, n int) float64 {
	format := fmt.Sprintf("%%.%df", n)
	res, _ := strconv.ParseFloat(fmt.Sprintf(format, f), 64)
	return res
}

func Str2Float64(data, dataType string) (float64, error) {
	dataType = strings.ToLower(dataType)

	switch dataType {
	case "float", "float32", "float64":
		v, err := strconv.ParseFloat(data, 64)
		return FloatRound(v, 4), err
	case "int", "int32", "int64":
		v, err := strconv.ParseInt(data, 10, 64)
		return float64(v), err
	default:
		return 0, fmt.Errorf("不支持的数据类型: %v", dataType)
	}
}
